﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NB.MGJ.Service;
using NB.MGJ.Model;
using System.Web.Security;
using NB.MGJ.Common.Cache;
using System.Threading.Tasks;

namespace NB.MGJ.Web.Controllers
{
    public class HomeController : Controller
    {
        private HomeService _HomeService = new HomeService();
        private ManagerService _ManagerService=new ManagerService();
        private CodeManageService _CodeManageService=new CodeManageService();
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<ActionResult> Index(LogOnModel model, string returnUrl)
        {
            if (string.IsNullOrWhiteSpace(model.UserName))
            {
                ModelState.AddModelError("", "登录名不能为空");
                return View(model);
                // return JavaScript("alert('登录名不能为空')");
            }
            if (string.IsNullOrWhiteSpace(model.Password))
            {
                ModelState.AddModelError("", "密码不能为空");
                return View(model);
            }
            model.UserName = model.UserName.Trim();
            model.Password = model.Password.Trim();

            int? userid = null;
            // 如果验证不通过
            if (!_HomeService.UserLogin(model.UserName, model.Password, out userid))
            {
                ModelState.AddModelError("", "用户名密码不正确");
                return View(model);
            }
            var _user = _HomeService.GetUserByUserId(userid.Value);
            if (_user == null)
            {
                ModelState.AddModelError("", "用户名数据信息丢失不存在");

                return View(model);
            }
            if (_user.EnterpriseId == 1 || _user.HeadId == 1)
            {
                var applylist = _CodeManageService.Getapplylist(_user.EnterpriseId);
                if (applylist.Count > 0)
                {
                    await Task.Run(() =>
                    {
                        NB.MGJ.SignalR.SignalR_MessagePush.SetMessageQueue(() =>
                        {
                            return _HomeService.GetUserNotReadMessage(_user.ID, new L.EntityModel.Sys_PushMessage
                            {
                                ID = NB.MGJ.Common.Constant.GetGuid32,
                                IsRead = 1,
                                ReciveUserId = _user.ID,
                                PushDate = DateTime.Now,
                                PushContent = "您有码申请信息暂未处理，请查阅清单"
                            });
                        }, false);
                    });
                }
            }
            if (_user.Distributor != 0)
            {
                var antifleeing_distributorrecalllogList = _CodeManageService.GetRecallListByDistributorId(_user.Distributor);
                if (antifleeing_distributorrecalllogList.Count > 0)
                {
                    await Task.Run(() =>
                    {
                        NB.MGJ.SignalR.SignalR_MessagePush.SetMessageQueue(() =>
                        {
                            return _HomeService.GetUserNotReadMessage(_user.ID, new L.EntityModel.Sys_PushMessage
                            {
                                ID = NB.MGJ.Common.Constant.GetGuid32,
                                IsRead = 1,
                                ReciveUserId = _user.ID,
                                PushDate = DateTime.Now,
                                PushContent = "您有商品尚待召回，请查阅清单"
                            });
                        }, false);
                    });
                }
            }


            var EModel = _ManagerService.GetEnterpriseModel_Eid(_user.EnterpriseId);
            if (EModel.EndTime <= DateTime.Now.AddDays(30))
            {

                await Task.Run(() =>
                {
                    NB.MGJ.SignalR.SignalR_MessagePush.SetMessageQueue(() =>
                    {
                        return _HomeService.GetUserNotReadMessage(_user.ID, new L.EntityModel.Sys_PushMessage
                        {
                            ID = NB.MGJ.Common.Constant.GetGuid32,
                            IsRead = 1,
                            ReciveUserId = _user.ID,
                            PushDate = DateTime.Now,
                            PushContent = "您的机构即将到期，请及时续费，以免影响您的使用"
                        });
                    }, false);
                });

            }
            if (EModel.EndTime < DateTime.Now)
            {

                await Task.Run(() =>
                {
                    NB.MGJ.SignalR.SignalR_MessagePush.SetMessageQueue(() =>
                    {
                        return _HomeService.GetUserNotReadMessage(_user.ID, new L.EntityModel.Sys_PushMessage
                        {
                            ID = NB.MGJ.Common.Constant.GetGuid32,
                            IsRead = 1,
                            ReciveUserId = _user.ID,
                            PushDate = DateTime.Now,
                            PushContent = "您的机构已到期，请及时续费，以免影响您的使用"
                        });
                    }, false);
                });

            }



            FormsAuthentication.SetAuthCookie(userid.ToString(), false);
            UserHelper.SetUserToSession(_user);
            await Task.Run(() =>
            {
                NB.MGJ.SignalR.SignalR_MessagePush.SetMessageQueue(() =>
                {
                    return _HomeService.GetUserNotReadMessage(_user.ID, new L.EntityModel.Sys_PushMessage
                       {
                           ID = NB.MGJ.Common.Constant.GetGuid32,
                           IsRead = 1,
                           ReciveUserId = _user.ID,
                           PushDate = DateTime.Now,
                           PushContent = "欢迎使用码管家云系统"
                       });
                }, false);
            });
            return RedictCallBack(returnUrl);
        }
        private ActionResult RedictCallBack(string returnUrl)
        {
            if (!string.IsNullOrWhiteSpace(returnUrl))
                return Redirect(returnUrl);
            return RedirectToAction("Index", "Manager");
        }
        /// <summary>
        /// 像客户数据库添加表字段
        /// </summary>
        /// <returns></returns>
        public string AddTableSize()
        {
            var temp = _HomeService.AddTableSizeService();
            return "";
        }

        /// <summary>
        /// 设置用户消息为已读
        /// </summary>
        [HttpPost]
        public void SetUserMessageToRead(string[] messageId)
        {
            if (messageId == null)
            {
                return;
            }
            _HomeService.SetUserMessageIsRead(messageId);
        }
    }
}